/*
  Copyright 2011 Jonathan Albarrán León

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.jaal.movilconsultanet.activities;

import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.jaal.movilconsultanet.R;
import com.jaal.movilconsultanet.SessionCookie;
import com.jaal.movilconsultanet.Util;
import com.jaal.movilconsultanet.XMLContent;
import com.jaal.movilconsultanet.asynctasks.CaptchaRequester;
import com.jaal.movilconsultanet.asynctasks.GSMSessionRestorer;

public class MovilConsultaNet extends Activity {

	// Campos de entrada
	private Button btnInicioSesion, btnRestoreSession;
	public EditText passwordField, numeroField;
	public Spinner codigoTlfField;

	// esto es para la sesion despues de entrar el captcha y numero y clave...

	private SessionCookie sessionCookie;

	public SessionCookie getSessionCookie() {
		return sessionCookie;
	}

	public void setSessionCookie(SessionCookie sessionCookie) {
		this.sessionCookie = sessionCookie;
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.start);
		
		AdView adView = (AdView) findViewById(R.id.adView0);
		AdRequest request = new AdRequest();
	    
	    request.addTestDevice(AdRequest.TEST_EMULATOR);
		adView.loadAd(request);

		sessionCookie = new SessionCookie();

		XMLContent.setContext(getApplicationContext());
		Util.setContext(getApplicationContext());

		checkLastSession(false);

		configureUI();

	}

	private boolean checkLastSession(boolean autoRestore){

		Map<String, String> mapa = XMLContent.getXML("sesiones");

		if (mapa != null) {

			sessionCookie.setSessionCookie(mapa.get("session_id"));
			sessionCookie.setGSMSessionStarted(Boolean.parseBoolean(mapa.get("session_started")));
			sessionCookie.setMobileId(("mobile_id"));

			if (sessionCookie.isGSMSessionStarted()) {
				if (autoRestore) {
					new GSMSessionRestorer(this).execute("");
				} else {
					Intent i = new Intent(this, Consulta.class);
					startActivity(i);
				}
				return true;
			}
		}
		return false;
	}

	private void configureUI() {

		btnInicioSesion = (Button) findViewById(R.id.btnInicioSesion);
		btnInicioSesion.setOnClickListener(mClickListener);

		btnRestoreSession = (Button) findViewById(R.id.btnSesionPrevia);
		btnRestoreSession.setOnClickListener(mClickListener);

		passwordField = (EditText) findViewById(R.id.editTextPassword);

		//		captchaField = (EditText) findViewById(R.id.editTextCaptcha);
		numeroField = (EditText) findViewById(R.id.editTextNumber);

		codigoTlfField = (Spinner) findViewById(R.id.codigoTlf);

		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.cod_tlf_array,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		codigoTlfField = (Spinner) findViewById(R.id.codigoTlf);

		codigoTlfField.setAdapter(adapter);


		//para recordar las sesiones anteriores
		Map<String, String> mapaSesiones = XMLContent.getXML("sesiones");

		if (mapaSesiones != null) {
			passwordField.setText(mapaSesiones.get("password"));
			numeroField.setText(mapaSesiones.get("number"));

			int i = adapter.getPosition(mapaSesiones.get("code"));

			codigoTlfField.setSelection(i);
		}
	}

	private void mostrarCaptchaDialog() {
		Log.d("MCN", "refrescarCaptcha - inicio");
		new CaptchaRequester(this)
		.execute("https://www.movilnet.com.ve/agl/login_agl.jpg");

		Log.d("MCN", "refrescarCaptcha - fin");
	}

	/*
	 * LISTENERS
	 */
	private OnClickListener mClickListener = new OnClickListener() {
		public void onClick(View v) {
			if (v.equals(btnInicioSesion)) {
				if (Util.isOnline()) {
					mostrarCaptchaDialog();
				}
			} 

			if (v.equals(btnRestoreSession)){
				if (!checkLastSession(false)) {
					Toast.makeText(MovilConsultaNet.this, getResources().getText(R.string.no_session), Toast.LENGTH_SHORT).show();
				}
			}
		}
	};


	private void acercaDe() {
		Intent i = new Intent(this, About.class);
		startActivity(i);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.start_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.show_about:
			acercaDe();
			return true;
		case R.id.start_session:
			if (Util.isOnline()) {
				mostrarCaptchaDialog();
			}
			return true;
		case R.id.restore_session:
			if (!checkLastSession(false)) {
				Toast.makeText(MovilConsultaNet.this, getResources().getText(R.string.no_session), Toast.LENGTH_SHORT).show();
			}
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}